package com.phonetools.commonutils.android.net

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build

/**
 * 判断网络是否可用
 * @return true=可用,false=不可用
 */
fun isNetWorkAvailable(context: Context): Boolean {
    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val network = connectivityManager.activeNetwork ?: return false
        val netCap = connectivityManager.getNetworkCapabilities(network) ?: return false
        return (netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                netCap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
    } else {
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }
}

/**
 * 检测wifi是否连接
 * @return true=连接,false=断开
 */
fun isWifiConnected(context: Context): Boolean {
    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val network = connectivityManager.activeNetwork ?: return false
        val netCap = connectivityManager.getNetworkCapabilities(network) ?: return false
        return netCap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
    } else {
        val networkInfo = connectivityManager.activeNetworkInfo ?: return false
        return networkInfo.type == ConnectivityManager.TYPE_WIFI
    }
}

/**
 * 检测数据是否连接
 * @return true=连接,false=断开
 */
fun Context.isDataConnected(context: Context): Boolean {
    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val network = connectivityManager.activeNetwork ?: return false
        val netCap = connectivityManager.getNetworkCapabilities(network) ?: return false
        return netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
    } else {
        val networkInfo = connectivityManager.activeNetworkInfo ?: return false
        return networkInfo.type == ConnectivityManager.TYPE_MOBILE
    }
}

